import axios from "axios"
import { Message,MessageBox } from "element-ui"
import utils from "@/plugins/utils.js"
import Router from '@/router/index.js' 

// 获取当前环境是否是开发环境
let dev = (() => {
    return process.env.NODE_ENV == "development" ? true : false
})()


let isToken =(()=>{
    return process.env.VUE_APP_IS_TOKEN =='isToken' ? true : false
})()
const errorHandle = function (error) {
    // 判断是响应错误还是
    let errCode = 200
    if (error.response) {
        errCode = error.response.status;
    } else {
        // 请求头错误

    }
    switch (errCode) {
        case 500:
            Message.error( "请求错误，500！！");
            break;
        case 404:
            Message.error( "请求错误，404！！");
            break;
        case 401:
            // 回到登陆
            MessageBox.confirm('身份登陆过期，请重新登陆！', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              }).then(() => {
                Router.push("/login")
              }).catch(() => {
                Router.push("/login")
              });
            break;
    }

    (error) => {
        // 拿到500 等的报错消息
        let errorMsg = error.response.data.message
        Message.error(errorMsg ? errorMsg : "请求错误,请刷新后重试！！！");
        return Promise.reject(error);
    }
    return Promise.reject(error);
}

let http = axios.create({
    baseURL: dev ? "/api" : '',
    timeout: 3000000
})
http.interceptors.request.use((config) => {
    // 判断是否开启token
    if(isToken){
        // 开启token
        let loginUlr = "/login";
        if(loginUlr == config.path){
            // 登陆不需要token
            return config
        }else{
            let token = utils.getToken("token");
            if(token){
                config.headers={
                    authorization: `Bearer ${token}`,
                }
            }else{
                // 跳转到登陆
                MessageBox.confirm('请先登录！', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                  }).then(() => {
                    Router.push("/login")
                  }).catch(() => {
                    Router.push("/login")
                  });
            }
            
        }
    }
    return config;
}, errorHandle)

http.interceptors.response.use((response) => {
    let result = response.data;
    if (result.code == 200 || result == 1) {
        // 把请求的数据返回出去
        return result.data
    } else {
        // 请求响应错误
        Message.error(result.message ? result.message : "请求错误,请刷新后重试！！！");
        return null;
    }
}, errorHandle)






http.get = function (params = {}, headers = {}) {
    return http({
        ...params,
        headers,
        method: "GET",
    })
}

http.post = function (data = {}, headers = {
    "Content-Type": 'application/json;charset=UTF-8'
}) {
    return http({
        method: 'POST',
        headers,
        ...data
    })
}

export default http